from dataclasses import dataclass

from injector import inject

from src.exception import FailException, UnauthorizedException,ValidateErrorException
from src.pkg import validate_error_json
from src.schema.user_schema import UserSchemaResp
from src.service import  UserService
from src.schema import UserSchema
from src.pkg.response import success_message,success_json
@inject
@dataclass
class UserHandler:
    user_service: UserService
    def login(self):
        req = UserSchema()
        if not req.validate():
            return validate_error_json(req.errors)
        userObj:dict = {
            "username":req.userName.data,
            "password":req.passWord.data
        }
        code = self.user_service.login(userObj)
        if code ==-1:
            raise ValidateErrorException("ユーザー名またはパスワードが間違っています")
        return success_json(code)
    def register(self):
        req = UserSchema()
        if not req.validate():
            return validate_error_json(req.errors)
        userObj: dict = {
            "username": req.userName.data,
            "password": req.passWord.data
        }
        code = self.user_service.register(userObj)
        if code ==-1:
            raise ValidateErrorException("ユーザーのパスワードは既に存在しています")
        elif code==200:
            return success_message("success")

    def getuser_info(self):
        data =self.user_service.getuser_info()
        resp = UserSchemaResp()
        return success_json(resp.dump(data))